<template>
  <div class="approval-sidebar">
    <Button
      :class="{'is-view': approvalSidebarVisiable}"
      @click="handleToggleSidebar"
      class="toggle-btn"
      ghost
      type="info"
    >{{ approvalSidebarVisiable ? '收起审批流程' :'查看审批流程' }}</Button>
    <div class="sidebar" v-if="approvalSidebarVisiable">
      <div class="sidebar-title">
        审批流程
        <Button
          v-permission:[disablePermission]='["approval:edit","construction:approval:edit",
            "supervisor:approval:edit","cevaluation:approval:edit",
            "sevaluation:approval:edit"]'
          @click="handleToggleIsView"
          class="edit-btn"
          size="small"
          type="info"
        >{{ isApprovalListView ? '编辑流程' : '完成'}}</Button>
      </div>
      <!-- 审批操作 -->
      <ApprovalNodeOpr :approvalNode="approvalNode" v-if="approvalOprVisiable" />

      <div class="approval-node-wrapper">
        <h4>审批流程</h4>
        <ApprovalNodeCard
          :isApprovalEdit="isApprovalEdit"
          :isApprovalListView="isApprovalListView"
          :isApprovalInit="isApprovalInit"
          :key="i"
          :index="i"
          :node="node"
          @on-add-click="handleCardAddClick(node, i)"
          @on-add-click-local="handleCardAddClickLocal(i)"
          @on-del-click="handleCardDelClick(node)"
          @on-del-click-local="handleCardDelClickLocal(i)"
          @on-edit-click="handleCardEditClick(node)"
          @on-edit-click-local="handleCardEditClickLocal(node,i)"
          v-for="(node, i) in approvalList"
        />
      </div>
      <Spin fix size="large" v-if="approvalLoading"></Spin>
    </div>

    <Modal
      @on-cancel="handleProcessModalCancel"
      class="process-modal"
      title="默认审批设置"
      v-model="processModalVisiable"
    >
      <Form :label-width="90" :model="nodeAddForm" :rules="nodeAddFormRules" ref="nodeAddForm">
        <FormItem label="审批名称" prop="approvalName">
          <Select
            @on-change="handleApprovalChange"
            label-in-value
            placeholder="请选择审批名称"
            v-model="nodeAddForm.approvalName"
          >
            <Option
              :key="item.code"
              :value="item.code"
              v-for="item in approvalNameList"
            >{{ item.dictdesc }}</Option>
          </Select>
        </FormItem>
        <FormItem label="审批人员" prop="approver">
          <Input
            @click.native="handleSelectPeopleClick"
            placeholder="请选择人员"
            v-model="nodeAddForm.approver"
          >
            <Icon slot="suffix" type="md-add" />
          </Input>
        </FormItem>
        <FormItem label="审批人员公司" prop="approvalCompany">
          <Input disabled placeholder="请输入流程编号" v-model="nodeAddForm.approvalCompany"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleProcessModalCancel">重置</Button>
        <Button @click="handleFlowNodeEidtOk" type="primary" v-if="isFlowNodeEdit">确认</Button>
        <Button @click="hanldeFlowNodeAddOk" type="primary" v-else>新增提交</Button>
      </div>
    </Modal>

    <ModalProcesser @on-select-success="handleTableSelect" v-model="selectProcesserModalVisiable" />
  </div>
</template>

<script>
import ApprovalNodeCard from './approval-node-card';
import ModalProcesser from './modal-processer';
import ApprovalNodeOpr from './approcal-node-opr';

import {
  getApprovalList,
  addApprovalNode,
  delApprovalNode,
  editApprovalNode
} from '@/api/approval';
import { getFlowType } from '@/api/message.js';
import { ApprovalNodeStatus, FlowTypeDic } from '@/config/cfg';

export default {
  components: {
    ApprovalNodeCard,
    ModalProcesser,
    ApprovalNodeOpr
  },
  props: {
    // 流程id,是否有流程id判断是新增流程还是编辑流程(作废)
    // 审批的数据id, 查询之后, 只有一条数据的时候并且id的isData存在并且等于"N",后台已经生产流程，否则没有流程
    id: {
      type: String | Number,
      required: true
    },
    nodeId: {
      type: String | Number
    },
    // 数据类型 可能是项目树，也可能是表(查询流程时使用)
    type: {
      type: String | Number,
      required: true
    },
    isApprovalInit: {
      type: Boolean
    },
    // 审批还是查看 default, approval
    model: {
      type: String,
      defaut: 'default'
    },
    flowType: {
      type: Number | String,
      required: true
    },
    disablePermission: {
      type: Boolean,
      default: false,
      required: false
    },
    // 编辑流程完成
    visible: {
      type: Boolean
    }
  },
  data () {
    return {
      isApprovalEdit: true, // 流程新增还是编辑
      // 查看审批流程
      approvalSidebarVisiable: false,
      // 查看流程和编辑流程切换
      isApprovalListView: true,
      approvalList: [], // 流程列表
      approvalLoading: false,
      processModalVisiable: false, // 审批节点编辑弹窗
      isFlowNodeEdit: false, // 审批流程节点是否编辑
      oprFlowNode: {}, // 编辑时候操作的审批节点
      curIndex: 0,
      nextIndex: null,
      nodeAddForm: {
        approvalName: '', // 被选中审批名称的id
        approver: '', // 审批人员
        approvalCompany: '', // 审批人员所在公司
        deptName: '', // 所在部门
        phone: '',
        approverId: '', // 审批人id
        approvalNameText: '' // 审批名称对应的文本
      },
      nodeAddFormRules: {
        approvalName: [{ required: true, message: '请选择审批流程' }],
        approver: [{ required: true, message: '请选择审批人员' }]
      },
      approvalNameList: [], // 审批名称list

      selectProcesserModalVisiable: false,

      approvalNode: {} // 审批的节点
    };
  },
  computed: {
    approvalOprVisiable () {
      return this.model === 'approval' && this.isApprovalListView;
    }
  },
  watch: {
    id: {
      handler: function (newV, oldV) {
        if (newV !== '0' && newV !== 0) {
          this.getApprovalInfo();
          this.isApprovalListView = true;
        }
      }
    },
    flowType: {
      handler: function (val, oldV) {
        val && this.getApprovalInfo(val);
        // val && this.getApprovalNameList(val);
      }
    }
  },
  created () {
    this.approvalSidebarVisiable = this.visible;
    if (this.visible) {
      this.getApprovalInfo();
    }
  },
  mounted () {
    this.getApprovalNameList(this.flowType);
    console.log(this.type);
  },
  methods: {
    handleToggleSidebar () {
      if (this.approvalSidebarVisiable) {
        this.handleSidebarClose();
      } else {
        this.handleSidebarOpen();
      }
      this.approvalSidebarVisiable = !this.approvalSidebarVisiable;
    },
    // sidebar收起
    handleSidebarClose () {
      this.isApprovalListView = true;
    },
    // sidebar打开
    handleSidebarOpen () {
      this.getApprovalInfo();
    },
    handleToggleIsView () {
      this.isApprovalListView = !this.isApprovalListView;
    },
    async getApprovalInfo (val) {
      console.log(this.flowType, '项目树的flowType是多少');
      console.log(val, '项目树的val是多少');
      const flowType = val || this.flowType;
      console.log(FlowTypeDic);
      this.approvalLoading = true;
      const data = {
        dataid: this.id,
        type: this.type,
        treenodeid: Number(this.nodeId),
        flowType: (typeof flowType) === 'string' ? flowType : FlowTypeDic[flowType]
      };
      const resp = await getApprovalList(data);
      this.approvalLoading = false;

      // console.log('流程信息 resp=>', JSON.stringify(resp.data.data, 2, 2));
      this.approvalList = resp.data.data;
      const firstNode = this.approvalList[0] || {};
      console.log(this.approvalList, '拿到的流程是啥');
      /**
       * 只有一条数据的时候并且id的isData存在并且等于"N",后台已经生产流程，否则没有流程
       */
      if (
        this.approvalList.length === 1 &&
        firstNode.isData &&
        firstNode.isData === 'N'
      ) {
        this.isApprovalEdit = false;
        this.$emit('is-approval-has', false);
      } else {
        this.isApprovalEdit = true;
        this.$emit('is-approval-has', true);
      }

      this.approvalList.forEach(item => {
        item.approvalCompany = item.approverUnit;
      });

      /**
       * 如果是审批状态，需要找出第一待审批的节点
       */
      if (this.model === 'approval') {
        this.approvalNode =
          this.approvalList.find(item => {
            // eslint-disable-next-line eqeqeq
            return item.flowState == ApprovalNodeStatus.WAIT;
          }) || {};

        // console.log(
        //   'this.approvalNode',
        //   JSON.stringify(this.approvalNode, 2, 2)
        // );
      }

      /**
       * @describe 处理每个节点后面是否可以添加，编辑
       *
       * 找到是已通过,退回上一步,退回发起人,已撤回,已结束的最后一个节点
       * 前面节点的不能编辑添加
       * 当前节点可以添加，不能编辑
       * 后面节点可以编辑，添加
       */

      const canNotEditStatusList = [
        ApprovalNodeStatus.PASS,
        ApprovalNodeStatus.BACK,
        ApprovalNodeStatus.BACK_FIRST,
        ApprovalNodeStatus.RECALL,
        ApprovalNodeStatus.EDN
      ];

      let i;
      this.approvalList.forEach((item, index) => {
        if (canNotEditStatusList.includes(Number(item.flowState))) {
          i = index;
        }
      });
      if (!i) i = 0;
      this.approvalList.forEach((item, index) => {
        const state = Number(item.flowState);
        // 1: '未开始', // 剩下的所有人都是未开始
        // 2: '待审批', // 流程发起的下一个节点就是待审批
        // 3: '已通过',
        // 4: '退回上一步',
        // 5: '退回发起人',
        // 6: '已撤回',
        // 7: '已结束'
        // if (i > index) {
        //   this.$set(item, 'canEdit', false);
        //   this.$set(item, 'canAdd', false);
        // }
        // if (i < index) {
        //   this.$set(item, 'canEdit', true);
        //   this.$set(item, 'canAdd', true);
        // }
        // if (i === index) {
        //   this.$set(item, 'canEdit', false);
        //   this.$set(item, 'canAdd', true);
        // }
        // 前置条件是，这个流程是编辑状态下的流程节点，初始化审批流程节点时，除了第一个默认节点，其他节点都可以编辑和修改
        this.$set(item, 'canAdd', state == 1 || state === 2);// 当节点状态是未开始或者待审批，它下面就可以添加节点
        this.$set(item, 'canEdit', state === 1);// 仅当节点状态是未开始，它这个节点才可以被编辑
        // 如果为最后一个节点，且为发起节点，则允许后面添加节点
        if (index == this.approvalList.length - 1) {
          this.$set(item, 'canAdd', state === 0);
        }
        if (state == 1 || state === 2) { item.canAdd = true; }
        if (state == 1) { item.canEdit = true; }
      });
    },
    // 审批设置弹窗,重置回调
    handleProcessModalCancel () {
      this.oprFlowNode = {};
      this.curIndex = 0;
      this.isFlowNodeEdit = false;
      this.$refs.nodeAddForm.resetFields();
    },
    async getApprovalNameList (flowType) {
      const type = this.getRelationType(flowType);
      // console.log(flowType,type,3383338);
      try {
        const resp = await getFlowType(type);
        // console.log('审批名称列表 res=>', resp);
        this.approvalNameList = resp.data.data || [];
        console.log('审批名称列表 res=>', this.approvalNameList);
      } catch (error) {
        console.error(error);
      }
    },
    getRelationType (value) {
      const map = [3, 7, 8, 9, 10];
      return map[value];
    },
    // 新增流程节点
    async  hanldeFlowNodeAddOk () {
      this.$refs.nodeAddForm.validate(async valid => {
        if (valid) {
          /**
           * 增加节点的时候新增流程和编辑流程分开处理
           * 编辑提交到后台
           * 新增本地处理
           */
          if (this.isApprovalEdit) {
            const data = {
              preNodeId: this.oprFlowNode.nodeId,
              approverId: this.nodeAddForm.approverId,
              nodeName: this.nodeAddForm.approvalName
              // dwmc: this.nodeAddForm.approvalCompany,
              // sprxm: this.nodeAddForm.approver,
              // phone: this.nodeAddForm.phone
            };
            // deptName: this.nodeAddForm.deptName
            /**
             * this.curIndex < 0,  preNode是firstProcessNode nextNode是approveList第一个
             * 0 < this.curIndex < approvalList.lengt-1
             * this.curIndex === approvalList.lengt-1  nextNode是nodeId是'END'
             */
            if (
              this.curIndex < this.approvalList.length - 1 &&
              this.curIndex > 0
            ) {
              const nextNode = this.approvalList[this.curIndex + 1] || {};
              data.nextNodeId = nextNode.nodeId;
            } else if (this.curIndex === this.approvalList.length - 1) {
              data.nextNodeId = 'END';
            } else {
              data.nextNodeId = this.approvalList[0].nodeId;
            }
            await addApprovalNode(data);
            // console.log('增加审批流程节点 res=>', resp);
            this.processModalVisiable = false;
            this.getApprovalInfo();
            this.handleProcessModalCancel();
          } else {
            const data = {
              nodeName: this.nodeAddForm.approvalNameText,
              approvalCompany: this.nodeAddForm.approvalCompany,
              approverName: this.nodeAddForm.approver,
              approverId: this.nodeAddForm.approverId,
              phone: this.nodeAddForm.phone,
              nodeNameId: this.nodeAddForm.approvalName
            };
            // deptName: this.nodeAddForm.deptName

            this.approvalList.splice(this.curIndex + 1, 0, data);
            this.processModalVisiable = false;
            this.handleProcessModalCancel();
            console.log(333, data, this.approvalList);
          }
        }
      });
    },
    // 编辑流程节点
    handleFlowNodeEidtOk () {
      this.$refs.nodeAddForm.validate(async valid => {
        if (valid) {
          /**
           * 编辑节点的时候新增流程和编辑流程分开处理
           * 编辑提交到后台
           * 新增本地处理
           */
          if (this.isApprovalEdit) {
            const data = {
              nodeid: this.oprFlowNode.nodeId,
              approverId: this.nodeAddForm.approverId,
              nodename: this.nodeAddForm.approvalName
              // dwmc: this.nodeAddForm.approvalCompany,
              // sprxm: this.nodeAddForm.approver
            };
            // console.log('修改节点 data=>', data);
            await editApprovalNode(data);
            this.processModalVisiable = false;
            this.getApprovalInfo();
            this.handleProcessModalCancel();
          } else {
            const data = {
              nodeName: this.nodeAddForm.approvalNameText,
              approvalCompany: this.nodeAddForm.approvalCompany,
              approverName: this.nodeAddForm.approver,
              approverId: this.nodeAddForm.approverId,
              nodeNameId: this.nodeAddForm.approvalName,
              phone: this.nodeAddForm.phone
            };
            this.approvalList.splice(this.curIndex, 1, data);
            this.processModalVisiable = false;
            this.handleProcessModalCancel();
          }
        }
      });
    },
    handleTableSelect (select) {
      this.nodeAddForm.approver = select.userName;
      this.nodeAddForm.approverId = select.userId;
      this.nodeAddForm.approvalCompany = select.dwName;
      this.nodeAddForm.phone = select.phone;
      this.nodeAddForm.deptName = select.deptName;
    },
    handleSelectPeopleClick () {
      this.selectProcesserModalVisiable = true;
    },
    // 已有流程新增审批节点
    handleCardAddClick (node, i) {
      this.oprFlowNode = node;
      this.curIndex = i;
      this.processModalVisiable = true;
    },
    handleCardAddClickLocal (i) {
      this.curIndex = i;
      this.processModalVisiable = true;
    },
    // 已有流程删除审批节点
    handleCardDelClick (node) {
      this.$Modal.confirm({
        title: '确认删除？',
        content: '<p>数据删除后不可恢复，请确认是否删除数据？</p>',
        loading: true,
        onOk: async () => {
          const nodeId = node.nodeId;
          // console.log('删除节点 req=>', nodeId);
          await delApprovalNode(nodeId);
          // console.log('删除节点 res=>', resp);
          this.getApprovalInfo();
          this.$Modal.remove();
        }
      });
    },
    handleCardDelClickLocal (i) {
      this.approvalList.splice(i, 1);
    },
    // 已有流程，编辑审批流程按钮
    handleCardEditClick (node) {
      console.log('编辑的节点 ', JSON.stringify(node, 2, 2));
      this.isFlowNodeEdit = true;
      this.oprFlowNode = node;
      this.nodeAddForm.approvalName = Number(node.nodeNameId);
      this.nodeAddForm.approver = node.approverName;
      this.nodeAddForm.approvalCompany = node.approverUnit;
      this.nodeAddForm.approverId = node.approverId;
      this.processModalVisiable = true;
    },
    handleCardEditClickLocal (node, i) {
      console.log('编辑的节点', JSON.stringify(node, 2, 2));
      this.isFlowNodeEdit = true;
      this.oprFlowNode = node;
      this.curIndex = i;

      this.nodeAddForm.approvalName = node.nodeNameId;
      this.nodeAddForm.approver = node.approverName;
      this.nodeAddForm.approvalCompany = node.approvalCompany;
      this.nodeAddForm.approverId = node.approverId;
      this.processModalVisiable = true;
    },
    // 选择审批名称后
    handleApprovalChange (item) {
      console.log(item);
      if (!item) return;
      this.nodeAddForm.approvalNameText = item.label;
    },

    // 向父组件提供的方法
    getApprovalData () {
      const approvalList = JSON.parse(JSON.stringify(this.approvalList));
      approvalList.shift();
      return approvalList.map(item => {
        return {
          nodename: item.nodeNameId,
          curuser: item.approverId
        };
      });
    },
    reset () {
      this.isApprovalListView = true;
      this.getApprovalInfo();
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .toggle-btn {
  position: fixed;
  background: #fff;
  padding: 5px;
  top: 160px;
  right: 0;
  &.is-view {
    right: 335px;
  }
  > span {
    -webkit-writing-mode: vertical-rl;
    writing-mode: vertical-rl;
    letter-spacing: 5px;
  }
}

.sidebar {
  position: fixed;
  background: #fff;
  width: 335px;
  top: 160px;
  right: 0;
  bottom: 0;
  border: 1px solid #eeeeee;
  overflow: auto;
  z-index: 9999;
}

.sidebar-title {
  text-align: center;
  height: 36px;
  line-height: 36px;
  background: #eeeeee;
  font-size: 14px;
  width: 100%;
  .edit-btn {
    position: absolute;
    right: 6px;
    top: 6px;
  }
}
.approval-node-wrapper {
  > h4 {
    padding: 5px;
  }
}
</style>
